/*
 * Copyright @ 苏州瑞云信息技术有限公司 All rights reserved.
 */
package cn.com.recloud.bbs.service.impl;

import cn.com.recloud.bbs.constant.MetaOptionConstant;
import cn.com.recloud.bbs.dao.*;
import cn.com.recloud.bbs.entity.*;
import cn.com.recloud.bbs.service.ArticleService;
import cn.com.recloud.bbs.service.MetaoptionService;
import cn.com.recloud.bbs.util.UserUtil;
import cn.com.recloud.bbs.vo.AppArticStatisticsVO;
import cn.com.recloud.bbs.vo.AppListArticVO;
import cn.com.recloud.core.constant.ErrorEnum;
import cn.com.recloud.one.spring.exception.OneException;
import cn.com.recloud.one.spring.service.impl.BaseServiceImpl;
import cn.com.recloud.one.spring.util.RequestUserUtils;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.*;

/**
 * @author keblea xie
 * @since 2020-06-10
 */
@Service
public class ArticleServiceImpl extends BaseServiceImpl<ArticleDao, bbs_article> implements ArticleService {
    @Resource
    ArticleDao articleDao;
    @Resource
    MetaoptionService metaoptionService;
    @Autowired
    private ArticleTypeDao typeDao;
    @Autowired
    private PostLikeLogDao likeLogDao;
    @Autowired
    private MyFavoriteLogDao favoriteLogDao;
    @Autowired
    private UserUtil userUtil;

    /**
     * 保存文章
     * @param bbs_article
     * @param status 2新增直接发布，1保存成草稿
     * @return
     */
    @Override
    @Transactional
    public String saveArticle(bbs_article bbs_article,String status) {
        metaoption metaoption = metaoptionService.findMetaOptionBySetNameAndValue(MetaOptionConstant.ARTICLE_STATUS,status);
        bbs_article.setBbs_article_status(metaoption.getValue());
        bbs_article.setBbs_article_statusname(metaoption.getName());
        if("2".equals(status)){
            bbs_article.setReleasedon(new Date());
            bbs_article.setReleasedby(RequestUserUtils.getUserId());
            bbs_article.setReleasedbyname(RequestUserUtils.getUserName());
        }
        if(articleDao.insert(bbs_article) > 0){
            return bbs_article.getBbs_articleid();
        }
        return null;
    }

    /**
     * 更新文章
     * @param bbs_article
     * @param status
     * @param flag
     * @return
     */
    @Override
    @Transactional
    public String updateArticle(bbs_article bbs_article,String status,String flag) {
        //编辑时发布
        if("2".equals(status)){
            metaoption metaoption = metaoptionService.findMetaOptionBySetNameAndValue(MetaOptionConstant.ARTICLE_STATUS,status);
            bbs_article.setBbs_article_status(metaoption.getValue());
            bbs_article.setBbs_article_statusname(metaoption.getName());
            bbs_article.setReleasedon(new Date());
            bbs_article.setReleasedby(RequestUserUtils.getUserId());
            bbs_article.setReleasedbyname(RequestUserUtils.getUserName());
        }
        if(StringUtils.isNotBlank(flag) && "flag".equals(flag)){
            articleDao.deleteAvater(bbs_article.getBbs_articleid());
        }
        if(articleDao.updateById(bbs_article) > 0){
            return bbs_article.getBbs_articleid();
        }
        return null;
    }


    /**
     * 文章发布与取消
     * @param idList
     * @param type
     * @return
     */
    @Override
    public boolean publishOrCancel(List<String> idList,String type) {
        List<bbs_article> bbsArticleList = new ArrayList<>();
        idList.forEach(item->{
            bbs_article bbsArticle = new bbs_article();
            //1草稿2发布
            if("1".equals(type)){
                metaoption metaoption = metaoptionService.findMetaOptionBySetNameAndValue(MetaOptionConstant.ARTICLE_STATUS,type);
                bbsArticle.setBbs_article_status(metaoption.getValue());
                bbsArticle.setBbs_article_statusname(metaoption.getName());
                bbsArticle.setReleasedon(null);
                bbsArticle.setReleasedby(null);
                bbsArticle.setReleasedbyname(null);
            }else{
                metaoption metaoption = metaoptionService.findMetaOptionBySetNameAndValue(MetaOptionConstant.ARTICLE_STATUS,type);
                bbsArticle.setBbs_article_status(metaoption.getValue());
                bbsArticle.setBbs_article_statusname(metaoption.getName());
                bbsArticle.setReleasedon(new Date());
                bbsArticle.setReleasedby(RequestUserUtils.getUserId());
                bbsArticle.setReleasedbyname(RequestUserUtils.getUserName());
            }
            bbsArticle.setBbs_articleid(item);
            bbsArticleList.add(bbsArticle);
        });
        return super.updateBatchById(bbsArticleList);
    }

    /**
     * 删除文章
     * @param idList
     * @return
     */
    @Override
    public boolean removeByIds(Collection<? extends Serializable> idList) {
        if(CollectionUtil.isEmpty(idList)){
            throw new OneException("请至少选择一条要删除的文章");
        }
        List<bbs_article> bbsArticles = articleDao.selectBatchIds(idList);
        //已发布文章的id
        List<String> ids = new ArrayList<>();
        for(bbs_article bbsArticle:bbsArticles){
            if(bbsArticle.getBbs_article_status().equals(MetaOptionConstant.RELEASE_STAUS_ABLE)){
                ids.add(bbsArticle.getBbs_articleid());
            }
        }
        if(!CollectionUtil.isEmpty(ids)){
            throw new OneException("已发布的文章不能删除");
        }
        articleDao.deleteBatchIds(idList);
        return true;
    }

    /**
     * 获取app列表的分类信息
     * @param typeId
     * @param pageIndex
     * @param pageSize
     * @return
     */
    @Override
    public List<AppListArticVO> listArticle(String typeId, Integer pageIndex, Integer pageSize) {
        Page<AppListArticVO> page = new Page<>(pageIndex,pageSize);
        if(StringUtils.isEmpty(typeId)) throw new OneException("类型参数不能为空！");
        //最新的列表数据
        bbs_article_type articleType = typeDao.selectOne(new QueryWrapper<bbs_article_type>().lambda().eq(bbs_article_type::getSeq,1).eq(bbs_article_type::getIs_sys,true));
        if(ObjectUtil.isEmpty(articleType)) throw new OneException(ErrorEnum.UNKNOWN);
        if(typeId.equals(articleType.getBbs_article_typeid())){
            List<AppListArticVO> bbsArticles = articleDao.selectAppList(page,"new",null);
            return bbsArticles;
        }
        //最热的列表数据
        articleType = typeDao.selectOne(new QueryWrapper<bbs_article_type>().lambda().eq(bbs_article_type::getSeq,2).eq(bbs_article_type::getIs_sys,true));
        if(ObjectUtil.isEmpty(articleType)) throw new OneException(ErrorEnum.UNKNOWN);
        if(typeId.equals(articleType.getBbs_article_typeid())){
            List<AppListArticVO> bbsArticles = articleDao.selectAppList(page,"most",null);
            return bbsArticles;
        }
        //推存的数据
        articleType = typeDao.selectOne(new QueryWrapper<bbs_article_type>().lambda().eq(bbs_article_type::getSeq,3).eq(bbs_article_type::getIs_sys,true));
        if(ObjectUtil.isEmpty(articleType)) throw new OneException(ErrorEnum.UNKNOWN);
        if(typeId.equals(articleType.getBbs_article_typeid())){
            List<AppListArticVO> bbsArticles = articleDao.selectAppList(page,"recommend",null);
            return bbsArticles;
        }
        List<AppListArticVO> bbs_articles = articleDao.selectAppList(page,"other",typeId);

        return bbs_articles;
    }

    /**
     * app详情获取数据统计信息
     * @param id
     * @return
     */
    @Override
    public AppArticStatisticsVO getAppArticleStatistics(String id) {
        //获取统计信息
        AppArticStatisticsVO vo = articleDao.selectAppStatistics(id);

        //状态字段封装
        bbs_post_like_log likeLog = likeLogDao.selectOne(new QueryWrapper<bbs_post_like_log>().lambda()
                .eq(cn.com.recloud.bbs.entity.bbs_post_like_log::getObject_id, id)
                .eq(cn.com.recloud.bbs.entity.bbs_post_like_log::getLike_by_id, userUtil.getUserId()));
        //判断带你赞状态
        if(ObjectUtil.isNotEmpty(likeLog)){
            vo.setPostLikeStatus("0");
        }else {
            vo.setPostLikeStatus("1");
        }
        bbs_my_favorite_log favoriteLog = favoriteLogDao.selectOne(new QueryWrapper<bbs_my_favorite_log>().lambda()
                .eq(cn.com.recloud.bbs.entity.bbs_my_favorite_log::getObject_id, id)
                .eq(cn.com.recloud.bbs.entity.bbs_my_favorite_log::getFavorite_by_id, userUtil.getUserId()));
        //判断收藏状态
        if(ObjectUtil.isNotEmpty(favoriteLog)){
            vo.setFavoriteStatus("0");
        }else {
            vo.setFavoriteStatus("1");
        }
        return vo;
    }

    /**
     * 删除封面
     * @param id
     * @return
     */
    @Override
    public boolean deleteAvater(String id) {
        int result = articleDao.deleteAvater(id);
        if(result > 0){
            return true;
        }
        return false;
    }
}
